package com.txy.domain.strategy.service.rule.chain.impl;

import com.txy.domain.strategy.model.vo.RuleLogicCheckTypeVO;
import com.txy.domain.strategy.repository.IStrategyRepository;
import com.txy.domain.strategy.service.armory.IStrategyDispatch;
import com.txy.domain.strategy.service.rule.chain.AbstractLogicChain;
import com.txy.domain.strategy.service.rule.chain.factory.LogicChainFactory;
import com.txy.types.common.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

@Slf4j
@Component("rule_weight")
public class RuleWeightLogicChain extends AbstractLogicChain {
    @Resource
    IStrategyRepository repository;

    @Resource
    private IStrategyDispatch dispatch;

    public Long userScore = 4500L;

    @Override
    public LogicChainFactory.LogicChainRes logic(Long strategyId, String userId) {
        log.info("规则过滤-权重范围 userId:{} strategyId:{} ruleModel:{}", userId, strategyId, "rule_weight");

        String ruleValue = repository.queryStrategyRuleValue(strategyId, LogicChainFactory.LogicModel.RULE_WIGHT.getCode());

        // 1. 根据用户ID查询用户抽奖消耗的积分值，本章节我们先写死为固定的值。后续需要从数据库中查询。
        Map<Long, String> analyticalValueGroup = getAnalyticalValue(ruleValue);
        if (null == analyticalValueGroup || analyticalValueGroup.isEmpty()) {
            return next().logic(strategyId, userId);
        }

        // 2. 转换Keys值，并默认排序
        List<Long> analyticalSortedKeys = new ArrayList<>(analyticalValueGroup.keySet());
//        Collections.sort(analyticalSortedKeys);
        analyticalSortedKeys.sort(Collections.reverseOrder()); // 从大到小排序

        // 3. 找出最小符合的值，也就是【4500 积分，能找到 4000:102,103,104,105】、【5000 积分，能找到 5000:102,103,104,105,106,107】
        Long nextValue = analyticalSortedKeys.stream()
                .filter(key -> userScore >= key)
                .findFirst()
                .orElse(null);


        if (nextValue != null) {
            Integer awardId = dispatch.getRandomAwardId(strategyId, analyticalValueGroup.get(nextValue));
            log.info("过滤规则-权重返回接管, awardId: {}", awardId);
            return LogicChainFactory.LogicChainRes.builder()
                    .ruleLogicCheckTypeVO(RuleLogicCheckTypeVO.TAKE_OVER)
                    .logicModel(LogicChainFactory.LogicModel.RULE_WIGHT)
                    .logicChainAward(LogicChainFactory.LogicChainAward
                            .builder().awardId(awardId)
                            .build())
                    .build();

        }

        log.info("过滤规则-权重范围放行");
        return next().logic(strategyId, userId);
    }

    private Map<Long, String> getAnalyticalValue(String ruleValue) {
        String[] ruleValueGroups = ruleValue.split(Constants.SPACE);
        Map<Long, String> ruleValueMap = new HashMap<>();
        for (String ruleValueKey : ruleValueGroups) {
            // 检查输入是否为空
            if (ruleValueKey == null || ruleValueKey.isEmpty()) {
                return ruleValueMap;
            }
            // 分割字符串以获取键和值
            String[] parts = ruleValueKey.split(Constants.COLON);
            if (parts.length != 2) {
                throw new IllegalArgumentException("rule_weight rule_rule invalid input format" + ruleValueKey);
            }
            ruleValueMap.put(Long.parseLong(parts[0]), ruleValueKey);
        }
        return ruleValueMap;
    }
}
